package cn.itcast.hotel;

import cn.itcast.hotel.constants.HotelIndexConstants;
import org.apache.http.HttpHost;
import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import java.io.IOException;

public class HotelIndexTest2  {

    private RestHighLevelClient client;

    @BeforeEach
    public void initClient()  {
        this.client = new RestHighLevelClient(RestClient.builder(
                HttpHost.create("http://192.168.200.131:9200")
        ));
    }

    /**
     * 创建索引库
     * @throws IOException
     */
    @Test
    public void createIndex() throws IOException {
        // 1.创建对应操作的请求对象
        CreateIndexRequest request = new CreateIndexRequest("hotel");
        // 2.准备请求的参数：DSL语句
        request.source(HotelIndexConstants.MAPPING_TEMPLATE, XContentType.JSON);
        // 3.发送请求
        CreateIndexResponse response = client.indices().create(request, RequestOptions.DEFAULT);

        System.out.println(response.isAcknowledged());

    }

    /**
     * 删除索引库
     * @throws Exception
     */
    @Test
    public void deleteIndex() throws Exception {
        //创建操作请求对象
        DeleteIndexRequest request = new DeleteIndexRequest("hotels");
        //调用client执行请求方法
        AcknowledgedResponse response = client.indices().delete(request,RequestOptions.DEFAULT);
        //解析响应结果
        System.out.println(response.isAcknowledged());
    }

    /**
     * 查询索引库是否存在
     */
    @Test
    public void exisIndex() throws Exception {

        //创建操作对象
        GetIndexRequest request = new GetIndexRequest("hotel");
        //调用client
        boolean exists = client.indices().exists(request, RequestOptions.DEFAULT);
        //处理响应结果
        System.out.println(exists?"索引库已存在":"索引库不存在");
    }



    @AfterEach
    public void closeClient() {
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
